package vma.nicici.chat.api.photos;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;

import org.apache.http.util.ByteArrayBuffer;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import vma.nicici.chat.communication.AsynchCallback;
import vma.nicici.chat.gson.Message;

public final class PhotosDb {

	private PhotosDb(String writeablePath) {
		this.writeablePath = writeablePath+"/";
	}
	
	private static PhotosDb inst = null;
	private String writeablePath;
	
	public static PhotosDb instance(Context context) {
		String path = context.getFilesDir().getPath().toString();
		//Log.d("image", "writeable path: " + path);
		
		if (inst == null)
			inst = new PhotosDb(path);
		
		return inst;
	}
	
	private String getPhotoUrl(Long fbUserId) {
		return "http://graph.facebook.com/"+String.valueOf(fbUserId)+"/picture";
	}
	
	private String getWriteablePath(Long fbUserId) {
		return writeablePath+String.valueOf(fbUserId)+".jpg";
	}
	
	public void getPhotoFromMessageAsynch(final Message msg, final AsynchCallback<Bitmap> callback) {
		if (msg.facebookUserID <= 0) {
			return;
		}
		
		final String filename = getWriteablePath(msg.facebookUserID);
		
		Thread t = new Thread(new Runnable() {
			@Override
			public void run() {
				Bitmap photo = getPhotoFromStorage(filename);
				if (photo == null) {
					Log.d("Image", "photo not found on disc, preparing for download");
					downloadFromUrl( getPhotoUrl(msg.facebookUserID) ,filename);
				    photo = getPhotoFromStorage(filename);
				}
				
				try {
					callback.onFinished(photo);
					
					
				} catch (IOException e) {
					e.printStackTrace();
				} catch (URISyntaxException e) {
					e.printStackTrace();
				}
			}
		});
		
		t.start();
		
		
	}
	
	private Bitmap getPhotoFromStorage(String filename) {
		return BitmapFactory.decodeFile(filename);
	}
 
	private void downloadFromUrl(String imageUrl, String fileName) {  
          try {
                  URL url = new URL(imageUrl); 
                  File file = new File(fileName);
 
                  Log.d("Image", "download begining");
                  Log.d("Image", "download url:" + url);
                  Log.d("Image", "downloaded file name:" + fileName);
                  URLConnection ucon = url.openConnection();
 
                  InputStream is = ucon.getInputStream();
                  BufferedInputStream bis = new BufferedInputStream(is);
                  ByteArrayBuffer baf = new ByteArrayBuffer(50);
                  int current = 0;
                  while ((current = bis.read()) != -1) {
                      baf.append((byte) current);
                  }
 
                  FileOutputStream fos = new FileOutputStream(file);
                  fos.write(baf.toByteArray());
                  fos.close();
             } catch (IOException e) {
                        Log.d("Image", "Error: " + e);
             }
        }
 
	
}
